package com.nbstar.film.spider.spider;

import com.nbstar.film.spider.http.HttpRequest;
import com.nbstar.film.spider.pojo.FilmInfo;
import com.nbstar.film.spider.filter.ReplaceBracketsNameFilter;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Slf4j
@Data
public class TVCatSpider extends BaseSpider {


    //private static Logger logger = LoggerFactory.getLogger(TVCatSpider.class);

    public enum MediaType {
        TV,
        FILM
    }

    private MediaType mediaType = MediaType.FILM;

    public TVCatSpider(MediaType type) {
        this.spiderName = "TVMAO";
        this.mediaType = type;
        registFilter(new ReplaceBracketsNameFilter());
    }

    private String getTvUri(String tvName) throws Exception {
        String url = "https://www.tvmao.com/query.jsp?keys=" + URLEncoder.encode(tvName,"utf-8");

        String html = "";
        if (null != firefoxDriverRequest) {
            html = firefoxDriverRequest.getHtml(url);
        } else {
            html = HttpRequest.httpsGet(url);
        }
        Document doc = Jsoup.parse(html);
        Element t_q_tab_drama = doc.getElementById("t_q_tab_drama");
        if (null == t_q_tab_drama) {
            log.error("{} get t_q_tab_drama error!", tvName);
            return "";
        }
        Elements links = t_q_tab_drama.select("a[href]");

        for (Element link : links) {
            String href = link.attr("href").trim();
            Elements img = link.select("img");
            String name = "";
            if (img.size() > 0) {
                name = img.get(0).attr("alt").trim();
            }


            System.out.println("name:" + name + " href=" + href);

            if (name.equals(tvName)) {

                return href;
            }


        }

        return "";
    }


    private String getFilmUri(String filmName) throws UnsupportedEncodingException {
        String url = "https://www.tvmao.com/query.jsp?keys=" + URLEncoder.encode(filmName,"utf-8") + "&ed=bOS7peWutuS6uuS5i%2BWQjW8%3D";

        String html = HttpRequest.httpsGet(url);
        Document doc = Jsoup.parse(html);
        Element t_q_tab_drama = doc.getElementById("t_q_tab_movie");
        if (null == t_q_tab_drama) {
            log.error("error to get t_q_tab_movie:{}" , filmName);
            return null;
        }
        Elements rtive = t_q_tab_drama.getElementsByClass("rtive");
        Elements links = rtive.select("a[href]");

        for (Element link : links) {
            String href = link.attr("href").trim();
            Elements img = link.select("img");
            String name = "";
            if (img.size() > 0) {
                name = img.get(0).attr("alt").trim();
            }


            System.out.println("name:" + name + " href=" + href);

            if (name.equals(filmName)) {

                return href;
            }


        }

        return "";
    }

    @Override
    public String getContentId(String filmName) throws Exception {

        if (mediaType.equals(MediaType.FILM)) {
            return getFilmUri(filmName);
        } else {
            return getTvUri(filmName);
        }


    }

    @Override
    public FilmInfo getFilmInfo(String filmName) throws Exception {
        if (StringUtils.isEmpty(filmName)) {
            return new FilmInfo();
        }
        String url = "https://www.tvmao.com" +filmName;

        FilmInfo filmInfo = new FilmInfo();

        String html = HttpRequest.httpsGet(url);
        Document doc = Jsoup.parse(html);
        Elements summaryInfo = doc.getElementsByClass("obj-info");
        if (summaryInfo.size() <= 0) {
            log.error("failure to find basic info:" + filmName);
            return filmInfo;
        }

        Elements lang = doc.getElementsByAttributeValue("itemprop", "inLanguage");
        if (lang != null) {
            filmInfo.setLanguage(lang.text());
        }

        String[] strInfo = summaryInfo.text().split("\\|");
        for (String s : strInfo) {
            System.out.println(s);
            if (s.contains("年")) {
                filmInfo.setArriveDate(s);
            }

            if (s.contains("共") && s.contains("集")) {
                filmInfo.setPartNum(s.replace("共", "").trim());
            }
        }

        Elements links = summaryInfo.select("a[href]");
        if (links.size() > 0) {
            filmInfo.setCategory(links.text());
        }


        Elements contentLocation = summaryInfo.get(0).getElementsByAttributeValue("itemprop", "contentLocation");
        if (contentLocation.size() > 0) {
            filmInfo.setArriveAddress(contentLocation.get(0).text().trim());
        }

        Elements content = doc.getElementsByClass("object-module-content");
        if (content.size() > 0) {
            filmInfo.setDesc(content.text().trim());
        }

        Elements score = doc.getElementsByClass("score");
        if (score.size() > 0) {
            filmInfo.setAverage(Double.parseDouble(score.text()));
        }

        Elements votes = doc.getElementsByClass("score-col");
        if (votes.size() > 0) {
            filmInfo.setVotes(Long.parseLong(votes.text().replaceAll("人评分", "")));
        }

        Elements actorInfo = doc.getElementsByClass("obj-actor-info clear");
        if (actorInfo.size() == 0) {
            return filmInfo;
        }

        String[] actors = actorInfo.text().split("\\|");
        for (String act : actors) {
            if (act.contains("导演:")) {
                filmInfo.setDirector(act.replace("导演:", "").trim());
            }

            if (act.contains("主演:")) {
                filmInfo.setActor(act.replace("主演:", "").replace("»更多", "").trim());
            }
        }

        //播出平台
        Elements tds = doc.getElementsByClass("pro-td1 pro-td");
        if (tds.size() > 0) {
            String result = "";
            String tvp[] = tds.text().replace("播出频道 ", "").split(" ");
            int count = 0;
            for (String t : tvp) {
                if (!result.contains(t)) {

                    if (count == 0) {
                        result += t;
                    } else {
                        result += "," + t;
                    }
                    count++;
                }


            }

            filmInfo.setOnlinePlatform(result);
        }

        filmInfo.setSuccess(true);
       // System.out.println(html);
        return filmInfo;
    }

}
